﻿using System;
using System.ComponentModel.Composition.Hosting;
using Microsoft.Web.Helpers.UrlShortener.Core;


public class UrlShortener
{
    public static dynamic Settings = new Settings();
    private static CompositionContainer _container;

    UrlShortener()
    {
        //todo make it a proper singleton
        if (null == _container)
            _container = CreateContainer();
    }

    public static string Shorten(string urlToShrink)
    {
        var urlShortner = new UrlShortener();

        return urlShortner.callShortenProvider(urlToShrink, Settings);
    }

    public static string Shorten(string urlToShrink, dynamic settings)
    {
        var urlShortner = new UrlShortener();

        return urlShortner.callShortenProvider(urlToShrink, settings);
    }

    private string callShortenProvider(string urlToShrink, dynamic settings)
    {
        string providerToCall = UrlShortenerStrings.PROVIDER_NAME_Bitly;

        if (null != settings.Provider)
            providerToCall = settings.Provider;

        IUrlShortener shorternService = _container.GetExportedValue<IUrlShortener>(providerToCall);

        return shorternService.Shortern(urlToShrink, settings);
    }

    private CompositionContainer CreateContainer()
    {
        var catalog = new AggregateCatalog();

        var thisAssembly = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
        catalog.Catalogs.Add(thisAssembly);

        //TODO: Is there a better way to get the correct path.
        if (null != AppDomain.CurrentDomain.RelativeSearchPath)
            catalog.Catalogs.Add(new DirectoryCatalog(AppDomain.CurrentDomain.RelativeSearchPath));
        else
            catalog.Catalogs.Add(new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory));

        return new CompositionContainer(catalog);
    }
}
